package com.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.dto.AccountDetailsDto;
import com.example.entity.dto.AccountDto;
import com.example.entity.vo.request.DetailsSaveVo;
import com.example.mapper.AccountDetailsMapper;
import com.example.mapper.AccountMapper;
import com.example.service.AccountDetailsService;
import com.example.service.AccountService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountDetailsServiceImpl
        extends ServiceImpl<AccountDetailsMapper, AccountDetailsDto>
        implements AccountDetailsService{

    @Resource
    private AccountService accountService;

    /**
     * 通过Id查找用户的详细信息
     * @param id 用户Id
     * @return 用户信息
     */
    @Override
    public AccountDetailsDto findAccountDetailsById(int id) {
        return this.getById(id);
    }

    /**
     * 更新用户信息
     * @param id 当前登录的账户
     * @param vo 前端填写的用户信息
     * @return 成功与否
     */
    @Override
    @Transactional
    public boolean saveAccountDetails(int id,DetailsSaveVo vo) {
        //先检查用户名是否被占用
        AccountDto account = accountService.findAccountByNameOrEmail(vo.getUsername());
        if(account == null || account.getId() == id){
            //修改account表
            boolean update = accountService.update()
                    .eq("id", id)
                    .set("username", vo.getUsername())
                    .update();
            if (!update) return false;
            //修改details表
            AccountDetailsDto dto = new AccountDetailsDto();
            BeanUtils.copyProperties(vo,dto);
            //还差个id，手动补上
            dto.setId(id);
            return this.saveOrUpdate(dto);
        }
        return false;
    }
}
